/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Patrick van der Velde
 * Marcus Cuda
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;

namespace dnAnalytics.LinearAlgebra.IO
{
    /// <summary>
    /// Creates a <see cref="Matrix"/> from a delimited text file. If the user does not
    /// specify a delimiter, then any whitespace is used.
    /// </summary>
    public class DelimitedMatrixReader : SingleMatrixReader
    {
        private static readonly Regex sWhite = new Regex(@"\s+");
        private readonly Regex mDelimiter;

        /// <summary>
        /// Constructs a <strong>DelimitedMatrixReader</strong> using any whitespace as a delimiter.
        /// </summary>
        public DelimitedMatrixReader()
        {
            mDelimiter = sWhite;
        }

        /// <summary>
        /// Constructs a <strong>DelimitedMatrixReader</strong> using the given delimiter.
        /// </summary>
        /// <param name="delimiter">The delimiter to use.</param>
        public DelimitedMatrixReader(char delimiter)
        {
            mDelimiter = new Regex(new string(delimiter, 1));
        }

        /// <summary>
        /// Constructs a <strong>DelimitedMatrixReader</strong> using the given delimiter.
        /// </summary>
        /// <param name="delimiter">The delimiter to use.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="delimiter"/> is <see langword="null" />.</exception>
        public DelimitedMatrixReader(string delimiter)
        {
            if (delimiter == null)
            {
                throw new ArgumentNullException("delimiter");
            }
            mDelimiter = new Regex(delimiter);
        }

        /// <summary>
        /// Performs the actual reading.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> to read the matrix from.</param>
        /// <param name="storageType">The <see cref="StorageType"/> for the new matrix.</param>
        /// <returns>
        /// A matrix containing the data from the <see cref="Stream"/>. <see langword="null"/> is returned if the <see cref="Stream"/> is empty.
        /// </returns>
        protected override Matrix DoReadMatrix(Stream stream, StorageType storageType)
        {
            IList<string[]> data = new List<string[]>();

            //max is used to supports files like:
            //1,2
            //3,4,5,6
            //7
            //this creates a 3x4 matrix:
            //1, 2, 0 ,0 
            //3, 4, 5, 6
            //7, 0, 0, 0
            int max = -1;
            TextReader reader = new StreamReader(new BufferedStream(stream));
            string line = reader.ReadLine();
            while (line != null)
            {
                line = line.Trim();
                if (line.Length > 0)
                {
                    string[] row = mDelimiter.Split(line);
                    max = System.Math.Max(max, row.Length);
                    data.Add(row);
                }
                line = reader.ReadLine();
            }

            Matrix ret = null;
            switch (storageType)
            {
                case StorageType.Dense:
                    ret = new DenseMatrix(data.Count, max);
                    break;
                case StorageType.Sparse:
                    ret = new SparseMatrix(data.Count, max);
                    break;
                default:
                    Debug.Assert(false);
                    break;
            }

            if (data.Count != 0)
            {
                for (int i = 0; i < data.Count; i++)
                {
                    string[] row = data[i];
                    for (int j = 0; j < row.Length; j++)
                    {
                        ret[i, j] = Double.Parse(row[j], NumberStyles.Any, null);
                    }
                }
            }
            reader.Close();
            reader.Dispose();
            return ret;
        }
    }
}
